package org.common.utils.rpc.net;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import org.common.utils.net.netty.core.NettyDecode;
import org.common.utils.rpc.net.serialization.RpcSerialization;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * RPC解码器
 * @author zhouzhibing
 * @date 2025/11/16 17:56
 */
@ChannelHandler.Sharable
public class RpcNettyDeCode extends NettyDecode {

    private static final Logger log = LoggerFactory.getLogger(NettyDecode.class);

    private final RpcSerialization serializable;

    public RpcNettyDeCode(RpcSerialization serializable) {
        this.serializable = serializable;
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, Object msg, List<Object> out) throws Exception {
        ByteBuf in = (ByteBuf) msg;
        try {
            in.markReaderIndex();
            int dataLength = in.readInt();
            byte[] data = new byte[dataLength];
            in.readBytes(data);

            Object message = serializable.deserialize(data);
            out.add(message);
        } catch (Exception e) {
            in.resetReaderIndex();
            log.error("RpcNettyDeCode decode error", e);
        }
    }
}
